/**
 * 
 */
package controller;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import model.BasicResult;

/**
 * A class that read a process output and store it in a {@link BasicResult}. Set modeStderr to store
 * the stderr instead of the stdout.
 * 
 * @author GRONOWSKI Stephane svan001@aol.com
 * 
 *         igsat 2010
 * 
 */
public class OutputReader implements Runnable {

	public static final int	PROBLEM_RETURN_VALUE	= 10;
	public static final int	DEFAULT_RETURN_VALUE	= 0;

	private boolean			modeStderr				= false;
	private InputStream		stream					= null;
	private BufferedReader	input					= null;
	private BasicResult		result;

	private int				returnValue				= DEFAULT_RETURN_VALUE;

	/**
	 * Create a {@link OutputReader}
	 * 
	 * @param stream
	 *            stream to listen
	 * @param res
	 *            {@link BasicResult} to output to write
	 * @param modeStderr
	 *            true to store the stderr
	 */
	public OutputReader(InputStream stream, BasicResult res, boolean modeStderr) {
		this.modeStderr = modeStderr;
		this.stream = stream;
		result = res;

		input = new BufferedReader(new InputStreamReader(stream));
	}

	@Override
	public void run() {
		System.out.println("demarre ouput reader, mode= " + modeStderr);
		try
		{
			String line = null;

			if (modeStderr)
				while ((line = input.readLine()) != null)
					// System.out.println("lit: " + line);
					result.addStderr(line + "\n");
			else
				while ((line = input.readLine()) != null)
					// System.out.println("lit: " + line);
					result.addStdout(line + "\n");
			returnValue = DEFAULT_RETURN_VALUE;
		} catch (IOException e)
		{
			e.printStackTrace();
			returnValue = PROBLEM_RETURN_VALUE;
		}
		finally
		{
			try
			{
				input.close();
			} catch (IOException e)
			{
				e.printStackTrace();
				returnValue = PROBLEM_RETURN_VALUE;
			}
		}

	}

	/**
	 * Return the modeStderr, true if it read the stderr.
	 * 
	 * @return the modeStderr
	 */
	public boolean getModeStderr() {
		return modeStderr;
	}

	/**
	 * Set the modeStderr.
	 * 
	 * @param modeStderr
	 *            the modeStderr to set
	 */
	public void setModeStderr(boolean modeStderr) {
		this.modeStderr = modeStderr;
	}

	/**
	 * Return the returnValue, PROBLEM_RETURN_VALUE if there was a problem, otherwise
	 * DEFAULT_RETURN_VALUE.
	 * 
	 * @return the returnValue
	 */
	public int getReturnValue() {
		return returnValue;
	}

}
